import time
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from sqlalchemy.orm import Session
from models import ApiCall

class AuditLogger(BaseHTTPMiddleware):
    """
    审计日志中间件：拦截所有 HTTP 请求与响应，记录接口访问审计信息到数据库。

    参数:
    - app: FastAPI 应用实例
    - session_factory: 会话工厂，用于创建 SQLAlchemy Session
    """

    def __init__(self, app, session_factory):
        """
        初始化审计日志中间件并保存会话工厂。
        """
        super().__init__(app)
        self.session_factory = session_factory

    async def dispatch(self, request: Request, call_next):
        """
        记录请求与响应摘要信息：endpoint、method、status_code、duration_ms、request_summary、response_summary。
        """
        start = time.perf_counter()
        req_sum = await request.body()
        response = await call_next(request)
        duration = int((time.perf_counter() - start) * 1000)
        try:
            with self.session_factory() as db:  # type: Session
                item = ApiCall(
                    endpoint=str(request.url.path),
                    method=request.method,
                    status_code=response.status_code,
                    duration_ms=duration,
                    request_summary=req_sum[:2048].decode("utf-8", errors="ignore"),
                    response_summary=str(response.headers)[:1024],
                )
                db.add(item)
                db.commit()
        except Exception:
            pass
        return response
